package com.haoze.nurseapp.service.impl;

import com.haoze.nurseapp.service.AppDownloadService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author embed
 */
@Service
public class AppDownloadServiceImpl implements AppDownloadService {

    @Override
    public void downloadApp(HttpServletResponse response) {
        //new 一个apk的文件对象
        String apkPath = "D:\\work\\app_download\\zhhl.apk";
        File file = new File(apkPath);
        try {
            if (file.exists()) {
                // 以流的形式下载文件。

                //先以输入流把文件输入到buffer中，再以输出流的形式输出
                InputStream fis = new BufferedInputStream(new FileInputStream(apkPath));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }
        } catch (Exception e) {
            System.out.println("下载文件错误"+e.getMessage());
        }
    }
}
